import axios from 'axios';
import type { IObject, IRes } from '../utils/interface';
axios.defaults.baseURL = 'http://123.57.78.161:8081';
// const baseUrl: string = 'http://123.57.78.161:8081';

// 响应拦截
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.message && error.message.includes('timeout')) {
      // openMessage({ type: 'error', message: '请求超时！' });
      return Promise.reject({ message: '请求超时！' });
    }
    let message: string = error.response.data.message;
    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面，并携带当前页面的路径
        // 在登录成功后返回当前页面，这一步需要在登录页操作。
        case 401:
          message = '身份验证失败，请关闭重新进入！';
          break;
        case 404:
          message = '接口不存在！';
          break;
        case 500:
          message = '请求参数错误！';
          break;
        default:
          break;
      }
    }
    console.log(message, 'message');
    return Promise.reject(error.response.data);
  },
);

const GET = (
  url: string,
  params: { [key: string]: any } = {},
  headers: { [key: string]: any } = {},
): Promise<IRes> => {
  return axios
    .get(`${url.trim()}`, {
      params,
      headers: {
        ...headers,
      },
    })
    .then((res) => res.data);
};

const POST = (
  url: string,
  params: { [key: string]: any } = {},
  headers: { [key: string]: any } = {},
): Promise<IRes> => {
  const newParams = new URLSearchParams({ ...params });
  return axios
    .post(`${url.trim()}`, newParams, {
      headers: {
        ...headers,
      },
    })
    .then((res) => res.data);
};
export { GET, POST };
